package com.crpc.core.compress.impl;

import com.crpc.common.crpcEnum.CrpcExceptionEnums;
import com.crpc.common.exception.CrpcException;
import com.crpc.core.compress.Compressor;

import java.io.ByteArrayOutputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * @author wzy
 * @version 1.0
 * @description:
 * @date 2023/9/30 19:54
 */
public class ZipCompressor implements Compressor {
    @Override
    public byte[] compress(byte[] bytes) {
        Deflater deflater = new Deflater();
        deflater.setInput(bytes);
        deflater.finish();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bytes.length);
        byte[] buffer = new byte[1024];

        while (!deflater.finished()) {
            int count = deflater.deflate(buffer);
            outputStream.write(buffer, 0, count);
        }

        deflater.end();
        return outputStream.toByteArray();
    }

    @Override
    public byte[] decompress(byte[] bytes) {
        Inflater inflater = new Inflater();
        inflater.setInput(bytes);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bytes.length);
        byte[] buffer = new byte[1024];

        try {
            while (!inflater.finished()) {
                int count = inflater.inflate(buffer);
                outputStream.write(buffer, 0, count);
            }
        } catch (DataFormatException e) {
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.COMPRESS_ERROR);
        }

        inflater.end();
        return outputStream.toByteArray();
    }
}
